package com.dbq.fast.business.product.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.product.ui.StatusView;
import com.dbq.fast.util.SystemUtil;
import com.stripe.android.Stripe;
import com.stripe.android.TokenCallback;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;
import com.stripe.android.view.CardMultilineWidget;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by yh on 2018/3/5.
 * 用于支持stripe支付
 */

public class StripeDialogFragment extends DialogFragment {

    @BindView(R.id.card_input_widget)
    CardMultilineWidget cardInputWidget;

    @BindView(R.id.stripe_pay_sure)
    Button stripePaySure;

    @BindView(R.id.rl_business)
    RelativeLayout rlBusiness;

    @BindView(R.id.status_view)
    StatusView statusView;

    @BindView(R.id.iv_close)
    ImageView closeSelf;

    public static final int PAY_SUCCESS = 200;
    public static final int PAY_FAILED = 400;
    public static final int PAYING = 500;

    private OnGetPayTokenStatusListener listener;
    private OnPaySuccessStatusListener paySuccessListener;

    private OnPayFailedStatusListener payFailedListener;
    private OnCancelListener cancelListener;
    private int status;


    public static StripeDialogFragment newInstance() {
        StripeDialogFragment instance = new StripeDialogFragment();
        return instance;
    }

    public StripeDialogFragment() {
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00ffffff));
        View rootView = inflater.inflate(R.layout.dialog_stripe_view, null);
        ButterKnife.bind(this, rootView);
        initListener();
        getDialog().setCanceledOnTouchOutside(false);
        //2018-04-23 ,朱，除中国外，其他国家都需要输入邮编
        cardInputWidget.setShouldShowPostalCode(!"CN".equals(SystemUtil.getCountry(getContext())));
        return rootView;
    }

    public void setCancelListener(OnCancelListener cancelListener) {
        this.cancelListener = cancelListener;
    }


    public interface OnCancelListener {
        void onCancel();
    }


    private void initListener() {
        closeSelf.setOnClickListener(v -> {

            StripeDialogFragment.this.dismiss();
        });
        stripePaySure.setOnClickListener(v -> {
            Card card = cardInputWidget.getCard();
            if (card == null) {
                Toast.makeText(getContext(), R.string.please_check_card_info, Toast.LENGTH_SHORT).show();
            } else {
                setPayStatus(PAYING);
                statusView.setVisibility(View.VISIBLE);
                rlBusiness.setVisibility(View.GONE);
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.STRIPE_CLICK_CREDIT_SUBMIT);
                Stripe stripe = new Stripe(getContext().getApplicationContext());
                stripe.setDefaultPublishableKey("pk_live_w72OxeOKFdrhwUzKMeAv80jU");
                stripe.createToken(card, new TokenCallback() {
                    @Override
                    public void onError(Exception error) {
                        statusView.setVisibility(View.GONE);
                        rlBusiness.setVisibility(View.VISIBLE);
                        Log.i("tagT", error.getMessage());
                        if (listener != null) {
                            listener.getTokenFailed();
                        }
                    }

                    @Override
                    public void onSuccess(Token token) {
                        statusView.setStatus(StatusView.PAYING);
                        if (listener != null) {
                            listener.payTokenSuccess(token.getId());
                        }
                    }
                });
            }
        });


        statusView.setOnPayStatusListener(new StatusView.OnPayStatusListener() {
            @Override
            public void paySuccess() {
                StripeDialogFragment.this.dismiss();
                if (paySuccessListener != null) {
                    paySuccessListener.onSuccess();
                }

            }

            @Override
            public void payFailed() {
                if (payFailedListener != null) {
                    payFailedListener.onFailed();
                }
                StripeDialogFragment.this.dismiss();
            }
        });
    }


    public interface OnGetPayTokenStatusListener {
        void payTokenSuccess(String token);

        void getTokenFailed();
    }


    public void setTokenListener(OnGetPayTokenStatusListener listener) {
        this.listener = listener;
    }

    public interface OnPaySuccessStatusListener {
        void onSuccess();
    }

    public interface OnPayFailedStatusListener {
        void onFailed();
    }

    public void setPaySuccessStatusListener(OnPaySuccessStatusListener paySuccessListener) {
        this.paySuccessListener = paySuccessListener;
    }

    public void setPayFailedStatusListener(OnPayFailedStatusListener payFailedListener) {
        this.payFailedListener = payFailedListener;
    }

    public int getPayStatus() {
        return status;
    }

    public void setPayStatus(int status) {
        this.status = status;
        if (status == PAY_SUCCESS) {
            statusView.setStatus(StatusView.PAY_SUCCESS);
        } else if (status == PAY_FAILED) {
            statusView.setStatus(StatusView.PAY_FAILED);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (getPayStatus() != PAY_FAILED && getPayStatus() != PAY_SUCCESS) {
            if (cancelListener != null) {
                cancelListener.onCancel();
            }
        }
        listener = null;
        paySuccessListener = null;
        cancelListener = null;
    }
}
